package cn.jilian.front.util;

import javax.servlet.http.HttpSession;

import org.thymeleaf.util.StringUtils;

import java.util.Date;
import java.util.Map;
import java.util.Objects;

public class SessionUtil {
	
	private static final String IMAGE_CODE="authCode";
	
	public static final String SMS_CODE="smsCode";
	
	public static final String EXPIR_TIME="expire_time";
	
	public static final String MOBILE="mobile";
	
	public static final String USER_INFO="userInfo";
	
	public static void cacheSmsCode(HttpSession session,String mobile,String smsCode,long duration) {
		session.setAttribute(MOBILE, mobile);
		session.setAttribute(SMS_CODE, smsCode);
		session.setAttribute(EXPIR_TIME, new Date().getTime()+duration);
	}
	
	public static Boolean checkValidateCode(HttpSession session,String mobile,String smsCode,String authCode) {
		return StringUtils.equalsIgnoreCase(session.getAttribute(IMAGE_CODE), authCode)
				&&StringUtils.equals(session.getAttribute(MOBILE), mobile)
				&&StringUtils.equals(session.getAttribute(SMS_CODE), smsCode)
				;
	}
	
	public static boolean checkLogin(HttpSession session){
		return session.getAttribute(USER_INFO)!=null;
	}
	public static void cacheUserInfo(HttpSession session,Map<String,Object> userInfo){
		session.setAttribute(USER_INFO, userInfo);
	}
	
	public static void clearImageCode(HttpSession session){
		session.setAttribute(IMAGE_CODE, null);
	}

    @SuppressWarnings("unchecked")
    public static Map<String, Object> getUserInfo(HttpSession session) {
        Object v = session.getAttribute(USER_INFO);
        if (v == null) return null;
        return (Map<String, Object>) v;
    }
    
    public static Long getUnitMetaId(HttpSession session){
    	Map<String, Object> v = getUserInfo(session);
        if (v == null) return null;
        return ((Number) v.get("unitMetaId")).longValue();
    }

    public static Long getUserId(HttpSession session) {
        Map<String, Object> v = getUserInfo(session);
        if (v == null) return null;
        return ((Number) v.get("userId")).longValue();
    }

    public static Long getUnitId(HttpSession session) {
        Map<String, Object> v = getUserInfo(session);
        if (v == null) return null;
        return ((Number) v.get("unitId")).longValue();
    }

    public static Long getFid(HttpSession session) {
        Map<String, Object> v = getUserInfo(session);
        if (v == null) return null;
        return ((Number) v.get("deptId")).longValue();
    }

    public static String getAuthCode(HttpSession session) {
        return Objects.toString(session.getAttribute(IMAGE_CODE), "");
    }
    
    public static void cacheImageAuthCode(HttpSession session,String code) {
    	session.setAttribute(IMAGE_CODE, code);
    }
}
